import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:mall/core/models/withdraw.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/providers/pages/mine/manage/withdraw_apply_model.dart';
import 'package:mall/core/providers/pages/mine/manage/withdraw_cancel_model.dart';
import 'package:mall/core/providers/pages/mine/manage/withdraw_delete_model.dart';
import 'package:mall/core/providers/pages/mine/manage/withdraw_query_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:mall/screens/manage/withdraw_edit_page.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class WithdrawPage extends StatelessWidget {
  static const routeName = '/WithdrawPage';
  final int args;

  WithdrawPage({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Api api = Provider.of(context, listen: false);
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => WithdrawQueryModel(api, args)),
        ChangeNotifierProvider(create: (context) => WithdrawApplyModel(api)),
        ChangeNotifierProvider(create: (context) => WithdrawCancelModel(api)),
        ChangeNotifierProvider(create: (context) => WithdrawDeleteModel(api))
      ],
      child: Scaffold(
        appBar: AppBar(
          title: Text('店铺结算'),
        ),
        body: Consumer<WithdrawQueryModel>(
          builder: (context, model, child) {
            switch (model.viewState) {
              case ViewState.busy:
                return Center(
                  child: CircularProgressIndicator(),
                );
              case ViewState.error:
                return Center(
                  child: Text(model.errorMessage),
                );
              case ViewState.success:
                return Column(
                  children: <Widget>[
                    Expanded(
                      child: _ListWidget(
                        list: model.list,
                        withdrawList: model.withdrawList,
                      ),
                    ),
                    _BottomWidget(),
                  ],
                );
              default:
                return Container();
            }
          },
        ),
      ),
    );
  }
}

class _ListWidget extends StatelessWidget {
  final RefreshController _refreshController = RefreshController();
  final List<Withdraw> list;
  final List<Withdraw> withdrawList;

  _ListWidget({
    Key key,
    @required this.list,
    @required this.withdrawList,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: _refreshController,
      child: ListView.separated(
        itemBuilder: (context, index) {
          return Container(
            child: _ListItemWidget(withdraw: list[index]),
          );
        },
        separatorBuilder: (context, index) {
          return Divider(
            height: 12,
            color: Colors.transparent,
          );
        },
        itemCount: list.length,
      ),
      enablePullDown: false,
      enablePullUp: withdrawList.length == 10,
      onLoading: () => _onLoadData(context),
    );
  }

  void _onLoadData(BuildContext context) async {
    WithdrawQueryModel model = Provider.of(context, listen: false);
    await model.loadData();
    _refreshController.loadComplete();
  }
}

class _ListItemWidget extends StatelessWidget {
  final Withdraw withdraw;

  const _ListItemWidget({
    Key key,
    @required this.withdraw,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Slidable(
      child: Stack(
        alignment: Alignment.centerRight,
        children: <Widget>[
          Column(
            children: <Widget>[
              _ListItemHeaderWidget(withdraw: withdraw),
              _ListItemFooterWidget(withdraw: withdraw),
            ],
          ),
          if (withdraw.auditStatus == Withdraw.AUDITING)
            Image.asset('assets/images/withdraw/img_auditing.png', width: 96),
        ],
      ),
      actionPane: SlidableDrawerActionPane(),
      secondaryActions: <Widget>[
        if (withdraw.auditStatus == Withdraw.NOT_APPLY)
          IconSlideAction(
            icon: Icons.check,
            caption: '申请审核',
            color: Colors.green,
            onTap: () => _onApplyClicked(context),
          ),
        if (withdraw.auditStatus == Withdraw.AUDITING)
          IconSlideAction(
            icon: Icons.clear,
            caption: '撤回',
            color: Colors.red,
            onTap: () => _onCancelClicked(context),
          ),
        if (withdraw.auditStatus == Withdraw.NOT_APPLY ||
            withdraw.auditStatus == Withdraw.AUDIT_FAIL)
          IconSlideAction(
            icon: Icons.clear,
            caption: '删除',
            color: Colors.red,
            onTap: () => _onDeleteClicked(context),
          ),
      ],
    );
  }

  /// 申请
  void _onApplyClicked(BuildContext context) async {
    WithdrawApplyModel withdrawApplyModel = Provider.of(context, listen: false);
    ViewState viewState = await withdrawApplyModel.withdrawApply(withdraw);
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(withdrawApplyModel.errorMessage);
        break;
      default:
        WithdrawQueryModel withdrawQueryModel = Provider.of(context, listen: false);
        withdrawQueryModel.refreshData();
        break;
    }
  }

  /// 撤回
  void _onCancelClicked(BuildContext context) async {
    WithdrawCancelModel withdrawCancelModel = Provider.of(context, listen: false);
    ViewState viewState = await withdrawCancelModel.withdrawCancel(withdraw);
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(withdrawCancelModel.errorMessage);
        break;
      default:
        WithdrawQueryModel withdrawQueryModel = Provider.of(context, listen: false);
        withdrawQueryModel.refreshData();
        break;
    }
  }

  /// 删除
  void _onDeleteClicked(BuildContext context) async {
    WithdrawDeleteModel withdrawDeleteModel = Provider.of(context, listen: false);
    ViewState viewState = await withdrawDeleteModel.withdrawDelete(withdraw);
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(withdrawDeleteModel.errorMessage);
        break;
      default:
        WithdrawQueryModel withdrawQueryModel = Provider.of(context, listen: false);
        withdrawQueryModel.refreshData();
        break;
    }
  }
}

class _ListItemHeaderWidget extends StatelessWidget {
  final Withdraw withdraw;

  const _ListItemHeaderWidget({
    Key key,
    @required this.withdraw,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      height: 45,
      child: Row(
        children: <Widget>[
          Image.asset(
            'assets/images/bank/ic_bank.png',
            width: 24,
            color: Colors.grey,
          ),
          SizedBox(width: 8),
          Expanded(
            child: Text.rich(
              TextSpan(
                text: '入账账号',
                style: TextStyle(fontSize: 17),
                children: [
                  TextSpan(
                    text: '  (${withdraw.bankCardId})',
                    style: TextStyle(fontSize: 12),
                  ),
                ],
              ),
            ),
          ),
          Text(withdraw.cardOwnerName, style: TextStyle(fontSize: 17)),
        ],
      ),
    );
  }
}

class _ListItemFooterWidget extends StatelessWidget {
  final Withdraw withdraw;

  const _ListItemFooterWidget({
    Key key,
    @required this.withdraw,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(12),
      color: Colors.white,
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text('服务类型：${withdraw.accountTypeName}'),
                    SizedBox(height: 4),
                    Text('服务费用：${withdraw.serviceFee}'),
                    if (withdraw.auditStatus == Withdraw.AUDIT_FAIL) ...[
                      SizedBox(height: 4),
                      Text('审核备注：${withdraw.auditNote}'),
                    ]
                  ],
                ),
              ),
              Text(
                '+${withdraw.amount}',
                style: TextStyle(color: Theme.of(context).accentColor, fontSize: 19),
              ),
              if (withdraw.auditStatus == Withdraw.AUDIT_FAIL)
                Container(
                  margin: EdgeInsets.only(left: 6),
                  child: Image.asset('assets/images/withdraw/img_audit_fail.png', width: 24),
                ),
              if (withdraw.auditStatus == Withdraw.AUDIT_SUCCESS)
                Container(
                  margin: EdgeInsets.only(left: 6),
                  child: Image.asset('assets/images/withdraw/img_audit_success.png', width: 24),
                ),
            ],
          ),
          SizedBox(height: 8),
          Divider(height: 1),
          SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                '申请时间：${withdraw.createTime}',
                style: TextStyle(color: Colors.grey, fontSize: 10),
              ),
              Text(
                '转款时间：${withdraw.withdrawTime.isNotEmpty ? withdraw.withdrawTime : '--:--:--'}',
                style: TextStyle(color: Colors.grey, fontSize: 10),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class _BottomWidget extends StatelessWidget {
  const _BottomWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.maxFinite,
      margin: EdgeInsets.all(16),
      child: RaisedButton(
        onPressed: () => _onEditClicked(context),
        child: Text('创建店铺提现'),
      ),
    );
  }

  void _onEditClicked(BuildContext context) async {
    var result = await Navigator.of(context).pushNamed(WithdrawEditPage.routeName);
    if (result is bool ? result : false) {
      WithdrawQueryModel model = Provider.of(context, listen: false);
      model.refreshData();
    }
  }
}
